package by.grsu.bso.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import by.grsu.bso.form.LoginForm;
import by.grsu.bso.model.ShoppingCartItem;
import by.grsu.bso.model.User;
import by.grsu.bso.service.ServiceManager;

public class LoginAction extends Action {

	private final static String SUCCESS = "success";
	private final static String FAILURE = "failure";

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		LoginForm loginForm = (LoginForm) form;
		User user = ServiceManager.getUserService().get(loginForm.getLogin(),
				loginForm.getPassword());

		if (user != null) {
			HttpSession session = request.getSession(true);
			/*
			 * 1. remove record in DB by ID 
			 * 2. update shoppingCart
			 * 3. remove session "user"
			 * 4. create session "user" with new parameters
			 */
			User userOld = (User) session.getAttribute("user");
			List<ShoppingCartItem> oldUserCartList = ServiceManager.getShoppingCartItemService().findAllByUserId(userOld.getId());
			List<ShoppingCartItem> newUserCartList = ServiceManager.getShoppingCartItemService().findAllByUserId(user.getId());
			List<Integer> preparentForDeleteCartIdList = new ArrayList<Integer>();
			
			if ((oldUserCartList != null) && (newUserCartList != null)){
				for(ShoppingCartItem oldUserItem:oldUserCartList){
					for(ShoppingCartItem newUserItem:newUserCartList){
						if (oldUserItem.getProductId() == newUserItem.getProductId() ){
							preparentForDeleteCartIdList.add(oldUserItem.getId());
						}
					}
				}
			}
			
			//delete all repeat products in oldUser
			for(Integer preparentItem:preparentForDeleteCartIdList){
				ServiceManager.getShoppingCartItemService().delete(preparentItem);				
			}
			
			ServiceManager.getShoppingCartItemService().update(userOld.getId(), user.getId());
			ServiceManager.getUserService().delete(userOld.getId());
			session.removeAttribute("user");

			session.setAttribute("user", user);
			response.sendRedirect(request.getContextPath());
			return mapping.findForward(SUCCESS);
		} else {
			return mapping.findForward(FAILURE);
		}

	}
}
